#!/bin/bash

echo ">>> Step 1: 清理旧包..."
yum remove -y mariadb-libs

echo ">>> Step ２: 安装MYSQL源和导入密钥..."
rpm -Uvh https://dev.mysql.com/get/mysql57-community-release-el7-9.noarch.rpm
rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022

echo ">>> Step ３: 安装服务端和客户端..."
yum install -y mysql-community-server mysql-community-client

echo ">>> Step ４: 启动MYSQL并设置开机自启..."
systemctl start mysqld
systemctl enable mysqld

echo ">>> Step 5: 取得临时密码..."
TEMP_PWD=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')

read -p ">>> 请输入新 root 密码（建议使用简单密码如 123456）： " NEW_PWD

mysql -uroot -p"$TEMP_PWD" --connect-expired-password <<EOF
-- 首先降低密码策略要求
SET GLOBAL validate_password_policy=0;
SET GLOBAL validate_password_length=4;
SET GLOBAL validate_password_mixed_case_count=0;
SET GLOBAL validate_password_number_count=0;
SET GLOBAL validate_password_special_char_count=0;

ALTER USER 'root'@'localhost' IDENTIFIED BY '${NEW_PWD}';

DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;
EOF

mysql -uroot -p"${NEW_PWD}" -e "SELECT '你已进入MySQL数据库，成功了!' AS welcome;" 2>/dev/null

echo ">>> 日常登录命令：mysql -uroot -p${NEW_PWD}"